import { _decorator, Component, Node, EventTouch, UITransform, Vec2, Vec3 } from 'cc';
import Joystick from '../../Example/Script/Joystick';
import SelfPlayer from '../../Example/Script/SelfPlayer';
import { Battle } from '../Battle';
import { Player } from '../Player/Player';
const { ccclass, property } = _decorator;

@ccclass('MapJoystick')
export class MapJoystick extends Component {
    @property(UITransform)
    Trans: UITransform = null;
    @property(SelfPlayer)
    SelfControl: SelfPlayer = null;
    @property(Joystick)
    Joystick: Joystick = null;
    @property(Node)
    guideNode: Node = null;

    private _playerController: Player;

    start() {
        this.node.on(Node.EventType.TOUCH_START, this.OnTouchStart, this);
        this.node.on(Node.EventType.TOUCH_END, this.OnTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.OnTouchMove, this);
    }

    // 当触摸开始时调用
    private OnTouchStart(event: EventTouch) {
        Battle.startGame = true;
        this.guideNode.active = false;
    }

    private OnTouchEnd(event: EventTouch) {
        if (this.Joystick.node.active) {
            this.Joystick.node.active = false;
            this.SelfControl.SetDirPos(null);
            // this.Joystick.SetCenter(new Vec3(0, 0));
        }
        else {
            let vec2 = event.getUILocation();
            if (this.Trans) {
                let vec3 = this.Trans.convertToNodeSpaceAR(new Vec3(vec2.x, vec2.y));
                this.SelfControl.SetTargetPos(vec3);
            }

        }
        if (this._playerController == null) {
            this._playerController = Battle.playerNode.getComponent(Player);
        }
        this._playerController.MoveToIdle();
    }

    private OnTouchMove(event: EventTouch) {
        let pos = event.getUILocation();
        if (!this.Joystick.node.active && Vec2.distance(pos, event.getUIStartLocation()) > 20) {
            this.Joystick.node.active = true;
            let pos = event.getUIStartLocation();
            this.Joystick.node.setWorldPosition(new Vec3(pos.x, pos.y));
        }
        if (this.Joystick.node.active) {
            this.Joystick.SetCenter(new Vec3(pos.x, pos.y));
            this.SelfControl.SetDirPos(this.Joystick.Direction);
        }
        if (this._playerController == null) {
            this._playerController = Battle.playerNode.getComponent(Player);
        }
        this._playerController.MoveTargetDirection(this.Joystick.Direction.x);
    }

}


